package cn.com.shaom.learning.sb.session.example1;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * ClassName: ServletSessionController
 * Description:
 * Date: 2018/1/10 19:50 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@RestController
public class ServletSessionController {

    /**
     * session 依赖于cookie，浏览器可以看到，修改。不安全。
     *
     * @param browser
     * @param request
     * @param session
     */
    @GetMapping("/servlet/session/{browser}")
    public void session(@PathVariable(name = "browser") String browser,
                        HttpServletRequest request, HttpSession session) {

        Object sessionAttribute = session.getAttribute("browser");
        if (sessionAttribute == null) {
            System.out.println("不存在session，设置browser=" + browser);
            session.setAttribute("browser", browser);
        } else {
            System.out.println("存在session，browser=" + sessionAttribute.toString());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName() + " : " + cookie.getValue());
            }
        }
    }
}
